package com.ljj.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.ljj.commonutils.R;
import com.ljj.servicebase.handler.MicroCloudException;
import com.ljj.vod.service.VodService;
import com.ljj.vod.utils.ConstantPropertiesUtils;
import com.ljj.vod.utils.InitClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/vod/video")
public class VodController {

    @Autowired
    private VodService vodService;

    /**
     * 上传视频到阿里云视频点播，返回视频ID
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping
    public R uploadVideo(MultipartFile file) throws IOException {
        String videoId = vodService.uploadVideo(file);
        return R.ok().data("videoId",videoId);
    }

    /**
     * 根据视频ID删除阿里云视频点播中的视频
     * 注意：这里的ID指的是阿里云视频点播服务中的视频ID编号
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id) throws ClientException {
        vodService.deleteVideoById(id);
        return R.ok();
    }

    /**
     * 批量删除阿里云点播视频
     * @param ids
     * @return
     * @throws ClientException
     */
    @DeleteMapping
    public R deleteVideos(@RequestParam("ids") List<String> ids) throws ClientException {
        vodService.deleteVideoByIds(ids);
        return R.ok();
    }

    //根据视频id获取视频凭证
    @GetMapping("auth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        try {
            //创建初始化对象
            DefaultAcsClient client =
                    InitClient.initVodClient(ConstantPropertiesUtils.KEY_ID, ConstantPropertiesUtils.KEY_SECRET);
            //创建获取凭证request和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //向request设置视频id
            request.setVideoId(id);
            //调用方法得到凭证
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            String playAuth = response.getPlayAuth();
            return R.ok().data("playAuth",playAuth);
        }catch(Exception e) {
            throw new MicroCloudException(20001,"获取凭证失败");
        }
    }

}
